package ws.jdbc.concurrent.driver.sqlserver;

import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLException;
import java.sql.Statement;
import ws.jdbc.concurrent.driver.sqlserver.tds.TDSMessage;
import static ws.jdbc.concurrent.driver.sqlserver.tds.rpc.StoredProcedures.*;

/**
 * Forward-only and updatable result set.
 * 
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class CResultSetForwardOnlyUpdatable extends CResultSet {

  protected CResultSetForwardOnlyUpdatable(TDSMessage message, Statement stmt, String sql) throws SQLException {
    super(message, stmt, sql, SP_CURSOROPEN_SCROLLOPT_FORWARD_ONLY, SP_CURSOROPEN_CCOPT_OPTIMISTIC);
    initUpdateValue();
  }

  /**
   * Must override because forward-only result sets don't allow to fetch the number of rows.
   * 
   * @return
   * @throws SQLException
   */
  @Override
  public boolean next() throws SQLException {
    ++currentRow;
    if (tdsResultSet.isEmpty() || !inCache()) {
      tdsResultSet = message.cursorFetch(tdsResultSet.getCursor(), SP_CURSORFETCH_FETCHTYPE_NEXT, currentRow, fetchSize);
      rsIndex = 0;
      forwardCache();
    } else {
      ++rsIndex;
    }
    if (tdsResultSet.isEmpty()) {
      return false;
    } else {
      return true;
    }
  }

  // <editor-fold defaultstate="collapsed" desc="Operations not supported by forward-only result set.">
  @Override
  public boolean previous() throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public boolean absolute(int row) throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public void afterLast() throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public void beforeFirst() throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public boolean first() throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public boolean last() throws SQLException {
    throw new SQLException(Messages.msg_forward_only);
  }

  @Override
  public boolean isAfterLast() throws SQLException {
    throw new SQLFeatureNotSupportedException(Messages.msg_forward_only);
  }

  @Override
  public boolean isBeforeFirst() throws SQLException {
    throw new SQLFeatureNotSupportedException(Messages.msg_forward_only);
  }

  @Override
  public boolean isFirst() throws SQLException {
    throw new SQLFeatureNotSupportedException(Messages.msg_forward_only);
  }

  @Override
  public boolean isLast() throws SQLException {
    throw new SQLFeatureNotSupportedException(Messages.msg_forward_only);
  }
  // </editor-fold>
}
